package org.jeecg.trace.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.jeecg.trace.dto.FaultStatisticsHeadDTO;
import org.jeecg.trace.dto.MesLotStatusDTO;
import org.jeecg.trace.dto.MesPackItemDTO;
import org.jeecg.trace.dto.ProductionTraceDTO;
import org.jeecg.trace.entity.MesLotStatus;
import org.jeecg.trace.mapper.MesLotStatusMapper;
import org.jeecg.trace.mapper.MesPackItemMapper;
import org.jeecg.trace.mapper.ProductionTraceMapper;
import org.jeecg.trace.service.IMesLotStatusService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.trace.vo.MesPackItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 产品批次表
 * @Author: shaolong
 * @Date: 2022-11-16
 * @Version: V1.0
 */
@Service
@Slf4j
public class MesLotStatusServiceImpl extends ServiceImpl<MesLotStatusMapper, MesLotStatus> implements IMesLotStatusService {

	@Autowired
	private MesLotStatusMapper mesLotStatusMapper;
	@Autowired
	private MesPackItemMapper mesPackItemMapper;
	@Autowired
	private ProductionTraceMapper productionTraceMapper;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		mesPackItemMapper.deleteByMainId(id);
		//把这里的删除给改了 改成按照id删
		Map<String, Object> map = new HashMap<>();
		map.put("REC_ID", id);
		mesLotStatusMapper.deleteByMap(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for (Serializable id : idList) {
			mesPackItemMapper.deleteByMainId(id.toString());
			mesLotStatusMapper.deleteById(id);
		}
	}

	@Override
	public Result<String> edit(MesLotStatus mesLotStatus) {
		LambdaUpdateWrapper<MesLotStatus> eq = new LambdaUpdateWrapper<MesLotStatus>();
		//自定义更新条件   .eq(MesLineCfg::getLine, mesLineCfg.getLine());
		boolean update = update(mesLotStatus, eq);
		return update ? Result.ok("修改成功!") : Result.error("修改失败!");
	}

	@Override
	public IPage<MesLotStatus> pageList(Page<MesLotStatus> page, MesLotStatus mesLotStatus) {
		return mesLotStatusMapper.pageList(page,mesLotStatus);
	}

	@Override
	public void exportXls(HttpServletRequest request, HttpServletResponse response, Map<String, String> map) {
		log.info("sql分页导出excel....");
		long start = System.currentTimeMillis();
		List<MesLotStatusDTO> list = mesLotStatusMapper.queryList(map);
		list.forEach(item->{
			switch (item.getStatus()) {
				case "1":
					item.setStatus("已完成");
					break;
				case "2":
					item.setStatus("进行中");
					break;
				case "3":
					item.setStatus("待称重");
					break;
				case "4":
					item.setStatus("已入箱");
					break;
				case "5":
					item.setStatus("已报废");
					break;
				default:
					item.setStatus("未定义");
					break;
			}
			switch (item.getUnit()) {
				case "0":
					item.setUnit("盒");
					break;
				case "1":
					item.setUnit("箱");
					break;
				default:
					item.setUnit("未定义");
					break;
			}
		});
		List<MesPackItemVO> mesPackItemVOList = new ArrayList<>();
		for (MesLotStatusDTO lot : list) {
			if (lot.getUnit().equals("盒")) {
				Map<String, String> paramMap = new HashMap<>();
				paramMap.put("line", lot.getLine());
				paramMap.put("lotno", lot.getLotno());
				List<MesPackItemDTO> parentList =mesPackItemMapper.getParentMesPackitem(paramMap);
				List<MesPackItemDTO> childList =mesPackItemMapper.getChildMesPackitem(paramMap);
				for (MesPackItemDTO child : childList) {
					MesPackItemVO mesPackItemVO = new MesPackItemVO();
					mesPackItemVO.setLine(child.getLine());
					mesPackItemVO.setWoid(child.getWoid());
					mesPackItemVO.setPackId(child.getPackId());
					mesPackItemVO.setUnitsn(child.getUnitsn());
					mesPackItemVO.setPartno(child.getPartno());
					mesPackItemVO.setFsn(child.getFsn());
					mesPackItemVO.setCtime(child.getCtime());
					if (!parentList.isEmpty()) {
						mesPackItemVO.setBoxId(parentList.get(0).getPackId());
					}
					mesPackItemVOList.add(mesPackItemVO);
				}
			} else  { //不是盒就是箱
				Map<String, String> paramMap = new HashMap<>();
				paramMap.put("line", lot.getLine());
				paramMap.put("lotno", lot.getLotno());
				List<MesPackItemDTO> childList =mesPackItemMapper.getChildMesPackitem(paramMap);
				for (MesPackItemDTO child : childList) {
					Map<String, String> paramMap1 = new HashMap<>();
					paramMap1.put("line", child.getLine());
					paramMap1.put("lotno", child.getUnitsn());
					List<MesPackItemDTO> childList1 =mesPackItemMapper.getChildMesPackitem(paramMap1);
					if (!childList1.isEmpty()) {
						for (MesPackItemDTO child1 : childList1) {
							MesPackItemVO mesPackItemVO = new MesPackItemVO();
							mesPackItemVO.setLine(child1.getLine());
							mesPackItemVO.setWoid(child1.getWoid());
							mesPackItemVO.setPackId(child1.getPackId());
							mesPackItemVO.setUnitsn(child1.getUnitsn());
							mesPackItemVO.setPartno(child1.getPartno());
							mesPackItemVO.setFsn(child1.getFsn());
							mesPackItemVO.setCtime(child1.getCtime());
							mesPackItemVO.setBoxId(lot.getLotno());
							mesPackItemVOList.add(mesPackItemVO);
						}
					} else {
						MesPackItemVO mesPackItemVO = new MesPackItemVO();
						mesPackItemVO.setLine(child.getLine());
						mesPackItemVO.setWoid(child.getWoid());
						mesPackItemVO.setPackId(child.getUnitsn());
						mesPackItemVO.setUnitsn(child.getUnitsn());
						mesPackItemVO.setPartno(child.getPartno());
						mesPackItemVO.setFsn(child.getFsn());
						mesPackItemVO.setCtime(child.getCtime());
						mesPackItemVO.setBoxId(lot.getLotno());
						mesPackItemVOList.add(mesPackItemVO);
					}

				}
			}
		}
		//定义easyExcel导出的对象
		ExcelWriter excelWriter = null;
		List<MesPackItemDTO> itemList = null;
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-disposition", "attachment;filename=demo.xls");
		//内容样式策略
		WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
		//垂直居中,水平居中
		contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
		contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
		contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
		contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
		contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);


		// 字体策略
		WriteFont contentWriteFont = new WriteFont();
		// 字体大小
		contentWriteFont.setFontHeightInPoints((short) 8);
		contentWriteCellStyle.setWriteFont(contentWriteFont);
		//头策略使用默认 设置字体大小
		WriteCellStyle headWriteCellStyle = new WriteCellStyle();
		WriteFont headWriteFont = new WriteFont();
		headWriteFont.setFontHeightInPoints((short) 10);
		headWriteCellStyle.setWriteFont(headWriteFont);
		List<String> unitsnList = mesPackItemVOList.stream().map(MesPackItemVO::getUnitsn).collect(Collectors.toList());
		List<ProductionTraceDTO> testDataList = null;
		if (!unitsnList.isEmpty()) {
			testDataList = productionTraceMapper.queryTestDataList(unitsnList);
		}

		ExcelWriterSheetBuilder writeSheet = EasyExcel.writerSheet(0,"包装追溯导出");
		writeSheet.head(MesPackItemVO.class)
				.registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle));
		ExcelWriterSheetBuilder itemSheet = null;
        if (testDataList != null && !testDataList.isEmpty()) {
			itemSheet = EasyExcel.writerSheet(1, "参数明细");
			itemSheet.head(ProductionTraceDTO.class)
					.registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle));
        }
        try {
			//查询条件
			//获取总数
//			List<String> recIds = new ArrayList<>();
//			if (map.containsKey("recId")) {
//				recIds = Arrays.asList(map.get("recId").split(","));
//			}
			//long count = productionTraceMapper.countAll(map, recIds);
			//计算开启的线程数
			//int loopNum = new Double(Math.ceil((double) count / PAGE_NUM)).intValue();
			//log.info("多线程查询，总数：{}，开启线程数：{}", count, loopNum);
			//队列存放数据库中查询导的数据
			//ArrayBlockingQueue<List<ProductionTraceDTO>> queue = new ArrayBlockingQueue<>(loopNum, true);
			//当数据为空时跳出写入循环
			//AtomicInteger atomicInteger = new AtomicInteger(loopNum);
			//并发查询数据
			//executeTask(queue, loopNum, count, map, recIds);
//			Page<ProductionTraceDTO> page = new Page<>(1,1000000);

			excelWriter = EasyExcel.write(response.getOutputStream()).build();
			//list = queue.poll(PAGE_SEARCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
//			excelWriter.write(list, writeSheet.build());
			excelWriter.write(mesPackItemVOList, writeSheet.build());
			if (testDataList != null && !testDataList.isEmpty()) {
				excelWriter.write(testDataList, itemSheet.build());
			}

			//读写分离式写入
//            while (list != null) {
//                excelWriter.write(list, writeSheet);
//                //跳出循环
//                if (0 == atomicInteger.decrementAndGet()) {
//                    break;
//                }
//            }
			long end = System.currentTimeMillis();
			log.info("导出耗时：" + (end - start));
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("文件导出报错，{}", e.getMessage());
		} finally {
			if (excelWriter != null) {
				excelWriter.finish();
			}
		}
	}
}
